import React from 'react';
import { Badge, TabBar, Toast } from 'antd-mobile';
import {
    AppOutline,
    UnorderedListOutline,
    UserOutline,
    SmileOutline
} from 'antd-mobile-icons';

import { useState, useEffect } from 'react';
import { useHistory, useLocation } from 'react-router-dom';
const Mytabbar = () => {
    const tabs = [
        {
            key: '/home',
            title: '首页',
            icon: <AppOutline />,
            badge: Badge.dot,
        },
        {
            key: '/car',
            title: '购物车',
            icon: <UnorderedListOutline />,
            badge: '5',
        },
        {
            key: localStorage.getItem('token') ? '/mine' : '/login',
            title: localStorage.getItem('token') ? '我的' : '登录',
            icon: localStorage.getItem('token') ? <SmileOutline /> : <UserOutline />,
        },
    ]
    // 获取 loc当前的路由信息
    const loc = useLocation();
    const [activeKey, setActiveKey] = useState('/home');
    // 点击切换路由页面
    const his = useHistory() // 相当于类组件中的this.props.history

    //当切换路由的时候, 设置对应的key的选中
    useEffect(() => {
        // console.log('loc', loc);
        setActiveKey(loc.pathname)
    }, [loc.pathname]);


    // console.log('loc-tabbar', loc);
    const changepageFn = (key) => {
        // console.log('key', key);
        // 修改选中的key
        //setActiveKey(key)
        // 跳转页面了, 
        // 当跳转的页面为购物车页面, 需要判断用户是否登录, 登录则正常可以访问购物车页面
        // 当用户未登录, 则提示请先登录, 并跳转到登录页
        if (key == '/car') {
            if (localStorage.getItem('token')) {
                // 说明已经登录
                his.push(key)
            } else {
                // 提示一下
                Toast.show({
                    content: '请先登录',
                    afterClose() {
                        his.push('/login')
                    }
                })
            }
            return
        }
        his.push(key)
    }
    return (
        <div style={{ position: 'fixed', bottom: 0, left: 0, width: '100%', background: 'white' }}>
            <TabBar activeKey={activeKey} onChange={changepageFn} safeArea >
                {tabs.map(item => (
                    <TabBar.Item key={item.key} icon={item.icon} title={item.title} />
                ))}
            </TabBar>
        </div>
    );
}

export default Mytabbar;
